<?php

namespace app\admin\controller;

use app\common\Common;
use think\facade\Request;
use think\facade\Cache;

// 抖音媒资管理
class TiktokMediaAssets extends Base
{
    private $uploadImgRequestUrl = 'https://open.douyin.com/api/playlet/v2/resource/upload/';
    private $uploadVideoRequestUrl = 'https://open.douyin.com/api/playlet/v2/resource/upload/';
    private $queryVideoRequestUrl = 'https://open.douyin.com/api/playlet/v2/video/query/';
    private $createVideoRequestUrl = 'https://open.douyin.com/api/playlet/v2/video/create/';
    private $editVideoRequestUrl = 'https://open.douyin.com/api/playlet/v2/video/edit/';

    // 获取公共参数
    public function getCommon()
    {
        $clientToken = Common::getTikTokDeveloperClientToken();
        return [
            'Content-Type:application/json',
            'access-token:' . $clientToken
        ];
    }

    /**
     * 图片上传
     * @param img_url 封面图片地址
     * @param video_id 短剧ID
     */
    public function imgUpload()
    {
        $params = Request::param();

        $body = [
            'resource_type' => 2,
            'ma_app_id' => config('tiktok.applet.appid'),
            'image_meta' => [
                'url' => $params['img_url']
            ],
        ];
        $header = self::getCommon();

        $result = Common::curlRequest($this->uploadImgRequestUrl, 'POST', json_encode($body), $header);
        $data = json_decode($result, true);

        $redis = Cache::store('redis')->handler();

        $redis->select(5);
        $redis->set(config('media_assets.tiktok_media_assets').$params['video_id'], $data['data']['image_result']['open_pic_id']);
        return Common::success(['open_pic_id' => $data['data']['image_result']['open_pic_id']]);
    }

    /**
     * 视频上传
     * @param video_url 视频地址mp4格式
     * @param video_id 短剧ID
     * @param title 视频标题
     * @param sort int 第多少集
     */
    public function videoUpload()
    {
        $params = Request::param();
        $redis = Cache::store('redis')->handler();

        $redis->select(5);
        $body = [
            'resource_type' => 1,
            'ma_app_id' => config('tiktok.applet.appid'),
            'video_meta' => [
                'url' => $params['video_url'],
                'title' => $params['title'],
                'format' => 'mp4',
                'use_dy_cloud' => true
            ],
        ];
        $header = self::getCommon();

        $result = Common::curlRequest($this->uploadVideoRequestUrl, 'POST', json_encode($body), $header);
        $data = json_decode($result, true);
        $redis->set(config('tiktok.media_assets.tiktok_media_id').$params['video_id'].'-'.$params['sort'], $data['data']['video_result']['open_video_id']);
        return Common::success(['open_video_id' => $data['data']['video_result']['open_video_id']]);
    }

    /**
     * 查询视频状态
     * @param video_id 短剧ID
     * @param sort int 第多少集
     */
    public function queryVideo()
    {
        $params = Request::param();
        $redis = Cache::store('redis')->handler();

        $redis->select(5);
        $mediaId = $redis->get(config('tiktok.media_assets.tiktok_media_id').$params['video_id'].'-'.$params['sort']);

        $body = [
            'video_id_type' => 1,
            'ma_app_id' => config('tiktok.applet.appid'),
            'open_video_id' => $mediaId
        ];
        $header = self::getCommon();

        $result = Common::curlRequest($this->queryVideoRequestUrl, 'POST', json_encode($body), $header);
        $data = json_decode($result, true);
        $status = $data['data']['status'];
        return Common::success();
    }

    /**
     * 创建短剧
     * @param video_id 短剧ID
     * @param title 短剧标题
     * @param sylloge 总集数
     * @param recommendation 短剧推荐语
     * @param desp 短剧简介
     * @param tag_list 短剧类目标签
     * @param ordinary_record_num 备案号
     */
    public function createVideo()
    {
        $params = Request::param();
        $redis = Cache::store('redis')->handler();

        $redis->select(5);
        $openPicId = $redis->get(config('tiktok.media_assets.tiktok_media_assets').$params['video_id']);

        $body = [
            'ma_app_id' => config('tiktok.applet.appid'),
            'album_info' => [
                'title' => $params['title'],
                'seq_num' => $params['sylloge'],
                'cover_list' => [$openPicId],
                'year' => date('Y'),
                'album_status' => 3,
                'recommendation' => $params['recommendation'],
                'desp' => $params['desp'],
                'tag_list' => [$params['tag_list']],
                'qualification' => 2,
                'record_info' => [
                    'ordinary_record_num' => $params['ordinary_record_num']
                ]
            ]
        ];
        $header = self::getCommon();

        $result = Common::curlRequest($this->createVideoRequestUrl, 'POST', json_encode($body), $header);
        $data = json_decode($result, true);
        $redis->set(config('tiktok.media_assets.tiktok_video_id').$params['video_id'], $data['data']['album_id']);
        return Common::success(['album_id' => $data['data']['album_id']]);
    }

    /**
     * 短剧编辑
     * @param video_id 短剧ID
     * @param sort int 第多少集
     * @param title 剧集标题 例：第1集
     */
    public function editVideo()
    {
        $params = Request::param();
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $albumId = $redis->get(config('tiktok.media_assets.tiktok_video_id').$params['video_id']);
        $openPicId = $redis->get(config('tiktok.media_assets.tiktok_media_assets').$params['video_id']);
        $mediaId = $redis->get(config('tiktok.media_assets.tiktok_media_id').$params['video_id'].'-'.$params['sort']);
        $body = [
            'ma_app_id' => config('tiktok.applet.appid'),
            'album_id' => $albumId,
            'episode_info_list' => [
                [
                    'title' => $params['title'],
                    'seq' => $params['sort'],
                    'cover_list' => [$openPicId],
                    'open_video_id' => $mediaId
                ]
            ]
        ];
        $header = self::getCommon();

        $result = Common::curlRequest($this->editVideoRequestUrl, 'POST', json_encode($body), $header);
        $data = json_decode($result, true);
        return Common::success(['album_id' => $data['data']['album_id']]);
    }
}